<template>
  <div class="app-container">
    <el-row>
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <el-form :model="filterForm" label-width="90px" class="demo-form-inline" :inline="true">
            <el-form-item label="配置名称">
              <el-input v-model="filterForm.configName" placeholder="请输入配置名称" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadData(1)">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="content-area">
          <el-card>
            <template #header>
              <el-button icon="plus" type="primary" @click="handleCreate">创建模板</el-button>
            </template>
            <el-table :data="tableData" border style="width: 100%" height="calc(100vh - 400px)">
              <el-table-column prop="templateName" label="配置名称" min-width="180" />
              <el-table-column prop="configType" label="事件类型" width="180" />
              <el-table-column prop="templateContent" label="短信模板" min-width="350" show-overflow-tooltip />
              <!-- <el-table-column prop="configValue" label="目标用户" min-width="180" /> -->
              <el-table-column prop="enabled" label="启用状态" width="100">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.enabled"
                    :active-value="true"
                    :inactive-value="false"
                    @change="handleSwitchChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column prop="updateTime" label="更新时间" width="180" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button type="primary" link size="small" @click="handleEdit(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="danger" link size="small" @click="handleDelete(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <template #footer class="table-footer">
              <div class="pager">
                <pagination
                  v-if="pageInfo.total > 0"
                  v-model:total="pageInfo.total"
                  v-model:page="pageInfo.pageNum"
                  v-model:limit="pageInfo.pageSize"
                  @pagination="loadData"
                />
              </div>
            </template>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <el-drawer v-model="drawerVisiable" direction="rtl">
      <template #header>
        {{ formData.id ? '编辑模板' : '创建模板' }}
      </template>
      <template #default>
        <el-form
          v-loading="submitLoading"
          style="width: 100%"
          :model="formData"
          label-width="100px"
          class="demo-form-inline"
          :inline="true"
        >
          <el-form-item label="配置名称">
            <el-input v-model="formData.templateName" placeholder="请输入配置名称" />
          </el-form-item>
          <el-form-item label="事件类型">
            <!-- <el-input v-model="formData.configType" placeholder="请输入事件类型" /> -->
            <el-select
              v-model="formData.configType"
              style="width: 200px"
              placeholder="请选择事件类型"
            >
              <el-option
                v-for="item in configTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用">
            <div style="width: 200px">
              <el-switch v-model="formData.enabled" :active-value="true" :inactive-value="false" />
            </div>
            <!-- <el-input v-model="formData.isEnabled" placeholder="请输入是否启用" /> -->
          </el-form-item>
          <el-form-item label="短信模板">
            <textarea
              ref="textareaRef"
              v-model="formData.templateContent"
              style="padding: 5px; width: 300px; border: 1px solid #dddddd; border-radius: 5px"
              placeholder="可点击下方按钮输入占位符"
              :rows="5"
            ></textarea>
            <div>
              <el-button link type="primary" @click="inputText(1)">批次截止时间</el-button>
              <el-button link type="primary" @click="inputText(2)">批次名称</el-button>
              <el-button link type="primary" @click="inputText(3)">驳回原因</el-button>
            </div>
          </el-form-item>
          <!-- <el-form-item label="目标用户规则" width="300px">
            <div>
              <select-tree
                ref="selectTreeRef"
                v-model="formData.targetUserRule"
                popper-class="template-select-tree-popper"
                :props="{
                  children: 'children',
                  value: 'id',
                  label: 'name',
                }"
                multiple
                :expand-on-click-node="false"
                :collapse-tags-tooltip="false"
                :collapse-tags="true"
                :check-strictly="true"
                :data="unitOptions"
                show-checkbox
              ></select-tree>
            </div>
          </el-form-item> -->
          <!-- <el-form-item label="发送时间规则">
            <el-input v-model="formData.sendTimeRule" placeholder="请输入发送时间规则" />
          </el-form-item> -->

          <!-- <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item> -->
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import useSearch from '@/hooks/template/useSearch';
import useTableData from '@/hooks/template/useTableData';
import useEdit from '@/hooks/template/useEdit';
import MessageConfigAPI from '@/api/message/config.api';
// import UnitAPI from '@/api/system/unit.api';
// import SelectTree from '@/components/SelectTree/index.vue';
const configTypeOptions = reactive<any>([
  { value: 'BATCH_PUBLISHED', label: '批次发布' },
  { value: 'SUBMIT_FOR_REVIEW', label: '提交审核' },
  { value: 'REVIEW_REJECTED', label: '审核驳回' },
  { value: 'DEADLINE_REMINDER', label: '截止提醒' },
]);
const { tableData, pageInfo, loadData } = useTableData();
const { filterForm, resetForm } = useSearch();
const { formData, resetFormData, submitFormData, deleteFormData } = useEdit();

const drawerVisiable = ref(false);
const handleCreate = () => {
  resetFormData();
  drawerVisiable.value = true;
};

/**
 * 占位符插入
 */
const textareaRef = ref<HTMLTextAreaElement>();
const inputText = (type: any) => {
  const textMap: any = {
    1: '{deadline}',
    2: '{batchName}',
    3: '{reason}',
  };
  if (textareaRef.value) {
    const start = textareaRef.value.selectionStart;
    const end = textareaRef.value.selectionEnd;
    const text = textareaRef.value.value;
    const newText = text.substring(0, start) + textMap[type] + text.substring(end);
    textareaRef.value.value = newText;
    textareaRef.value.focus();
    setTimeout(() => {
      if (textareaRef.value) {
        textareaRef.value.setSelectionRange(
          start + textMap[type].length,
          start + textMap[type].length
        );
      }
    });
  }
};
/**
 * 表间操作
 */
const handleSwitchChange = (row: any) => {
  submitFormData({
    id: row.id,
    enabled: row.enabled,
  })
    .then(() => {
      ElMessage.success('状态更新成功');
    })
    .catch((error: any) => {
      console.error('状态更新失败:', error);
      ElMessage.error('状态更新失败');
      row.enabled = !row.enabled; // 恢复原始状态
    });
};
const handleEdit = (row: any) => {
  resetFormData();
  drawerVisiable.value = true;
  MessageConfigAPI.getConfigById(row.id).then((data: any) => {
    formData.value = { ...data };
  }).catch((err) => {
    
  });
};
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该模板吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => deleteFormData(row.id))
    .then(() => {
      ElMessage.success('删除成功');
      loadData(1);
    });
};
/**
 * 提交
 */
const submitLoading = ref(false);
const submit = () => {
  submitFormData()
    .then(() => {
      ElMessage.success('提交成功');
      loadData(1);
      drawerVisiable.value = false;
    })
    .finally(() => {
      submitLoading.value = false;
    });
};
const cancelClick = () => {
  drawerVisiable.value = false;
  resetFormData();
};
/**
 * 单位初始化
 */
// const unitOptions = ref<any>([]);
// const initUnit = () => {
//   UnitAPI.getTree().then((res: any) => {
//     unitOptions.value = res;
//   });
// };
onMounted(() => {
  // initUnit();
  loadData();
});
</script>
<style lang="scss">
.template-select-tree-popper {
  width: 400px !important;
}
</style>
<style lang="scss" scoped></style>
